﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using Code.DAL;

namespace Code.BLL
{
    /// <summary>
    /// 表UserAddChildConfig的管理类
    /// </summary>
    public class AddChildConfigManage:ManageBase<UserAddChildConfig>
    {
        /// <summary>
        /// 获取指定用户当前所乘配额
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public UserAddChildConfig GetNowAddChildConfig(Guid uid)
        {
            var list = base.Select(s => s.Where(p => p.Users.ID == uid || p.Users.CommandID == uid).Select(p => new { config = p, p.Users.UserType })).ToArray();
            var result = list.FirstOrDefault(p => p.config.UserID == uid);
            var temp = list.Where(p => p.config.UserID != uid);
            result.config.AllChildCount -= temp.Sum(p => p.config.AllChildCount) + temp.Count();
            return result.config;
        }
        /// <summary>
        /// 修改所有代理配额
        /// </summary>
        /// <param name="allChildCount">所有下级配额增量</param>
        /// <param name="allSurrogateCount">所有代理配额增量</param>
        /// <returns></returns>
        public int UpdateAll(int allChildCount)
        {
            var update = new NameValue<string, object>
            {
                {"AllChildCount",new OpteratorValue(Opterator.Add,allChildCount)}
            };
            var where = new NameValue<string, object>
            {
                {"NULL",new SqlExpression("UserID in (select ID from Users where CommandID is NULL)",(short)UserType.Surrogate)}
            };
            return base.Update(update, where);
        }
    }
}
